package cn.tedu.boot14.controller;

import cn.tedu.boot14.entity.User;
import cn.tedu.boot14.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        //把接收到的用户信息添加到user表中
        //获取链接
        try (Connection conn= DBUtils.getConn()){
            String sql="insert into user values(null,?,?,?)";
            PreparedStatement ps=conn.prepareStatement(sql);
            //替换?的内容
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNick());
            //执行SQL语句
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功";
    }
    @RequestMapping("/login")
    @ResponseBody
    public String login(String username,String password){
        try (Connection conn=DBUtils.getConn()){
            String sql="select password from user where username=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs=ps.executeQuery();
            if (rs.next()){
                String pw=rs.getString(1);
                if (pw.equals(password)){
                    return "登入成功";
                }else {
                    return "密码错误";
                }
            }
            return "用户名不存在";
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "";
    }
}
